import { Channel, Articles } from "@/types/data";
import { HomeAction } from "@/types/store";
import { sortBy } from "lodash";
type HomeState = {
  [x: string]: any;
  userChannel: Channel[];
  restChannel: Channel[];
  channelActiveKey: string;
  channelArticles: {
    [key: number]: Articles;
  };
};
const initialState: HomeState = {
  userChannel: [],
  restChannel: [],
  channelActiveKey: "",
  channelArticles: {},
};
const Home = (state = initialState, action: HomeAction): HomeState => {
  switch (action.type as string) {
    case "home/getUserChannel":
      if (Array.isArray(action.payload)) {
        return {
          ...state,
          userChannel: action.payload,
          channelActiveKey: action.payload[0]?.id + "",
        };
      }
      return state;
    case "home/getAllChannel":
      if (Array.isArray(action.payload)) {
        return {
          ...state,
          restChannel: action.payload,
        };
      }
      return state;
    case "home/changeTab":
      return {
        ...state,
        channelActiveKey: String(action.payload),
      };
    case "home/getChannelArticles":
      const { channelId, data } = action.payload as {
        channelId: number;
        data: Articles;
      };
      const curChannelArticles = state.channelArticles[channelId] ?? {
        pre_timestamp: null,
        results: [],
      };
      return {
        ...state,
        channelArticles: {
          ...state.channelArticles,
          [channelId]: {
            pre_timestamp: data.pre_timestamp,
            results: [...curChannelArticles.results, ...data.results],
          },
        },
      };
    case "home/delChannel":
      const delPayload = action.payload as Channel;
      return {
        ...state,
        // 删除当前频道
        userChannel: state.userChannel.filter(
          (item) => item.id !== delPayload.id
        ),
        restChannel: sortBy([...state.restChannel, delPayload], "id"),
      };
    case "home/addChannel":
      const delPayloads = action.payload as Channel;
      if (typeof action.payload === "string") {
        return state;
      }
      return {
        ...state,
        userChannel: [...state.userChannel, delPayloads],
        restChannel: state.restChannel.filter(
          (item) => item.id !== delPayloads.id
        ),
      };
    default:
      return state;
  }
};

export default Home;
